package com.xxxx;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.checkpoint.ListCheckpointed;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class HelloFlinkOperator {

    public static void main(String[] args) throws Exception {
        //获取执行环境
        StreamExecutionEnvironment environment = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //获取数据源
        DataStreamSource<String> source = environment.socketTextStream("192.168.88.101", 18880);
        //开始进行转换,Lambda 一定要主要添加返回类型
        SingleOutputStreamOperator<String> flatMap = source.flatMap((String line, Collector<String> collector) -> {
            Arrays.stream(line.split(" ")).forEach(word -> collector.collect(word));
        }).returns(Types.STRING);
        //开始转换
        flatMap.map(new StateMapFunction()).keyBy(0).sum(1).print();

        //启动流式计算
        environment.execute("WordCountApp" + System.currentTimeMillis());

    }

}

class StateMapFunction implements MapFunction<String, Tuple2<String, Integer>>, ListCheckpointed<Integer> {

    private int count = 0;

    @Override
    public Tuple2<String, Integer> map(String word) throws Exception {
        ++count;
        return Tuple2.of(word, 1);
    }


    @Override
    public List<Integer> snapshotState(long checkpointId, long timestamp) throws Exception {
        return Collections.singletonList(1);
    }

    @Override
    public void restoreState(List<Integer> list) throws Exception {
        for (Integer num : list) {
            count += num;
        }
    }


}